<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">账号管理</p>
    </div>
    <div class="view-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="用户账号" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width:230px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            size="small"
            style="width:230px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" class="list-search btn-success" color="#5ED4D4"
            @click="handleQuery"
          >搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" class="list-search"
            @click="resetQuery"
          >重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            class="btn-success"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:user:add']"
          >新建</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="userList" border>
        <el-table-column label="序号" type="index" align="center" width="50">
           <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户编号" align="center" key="userId" prop="userId" width="100" />
        <el-table-column label="用户账号" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户类型" align="center" key="userType" prop="userType" />
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.userId !== 1"
              v-hasPermi="['system:user:edit']"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-key"
              v-hasPermi="['system:user:resetPwd']"
              @click="handleResetPwd(scope.row)"
            >编辑密码</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.userId !== 1"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:user:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或编辑用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" noOptionsText="暂无数据" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="(userId == tenantId || userId == 1) && isAdd == true">
          <el-col :span="12">
            <el-form-item label="角色选择">
              <el-select v-model="form.roleIds" multiple placeholder="请选择" filterable>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.roleId == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="(form.userId !== form.tenantId || userId == 1) && isEdit == true">
          <el-col :span="12">
            <el-form-item label="角色选择">
              <el-select v-model="form.roleIds" multiple placeholder="请选择" filterable>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.roleId == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="btn-success mr20 width100" @click="submitForm">确 定</el-button>
        <el-button class="width100" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, editUser, resetUserPwd } from "@/api/system/setting/user/user";
import { treeselect } from "@/api/system/setting/dept/dept";
import { listRole } from "@/api/system/setting/role/role";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "userList",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      userId: '',
      tenantId: '',
      isAdd: false,
      isEdit: false
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    let userInfo = this.$store.state.user.users
    this.userId = userInfo.userId
    this.tenantId = userInfo.tenantId
  },
  methods: {
    // 获取用户列表
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams)).then(res => {
          this.userList = res.rows
          this.total = res.total
          this.loading = false
        }
      )
    },
    // 获取部门下拉树结构
    getTreeselect() {
      treeselect({status: 0}).then(res => {
        this.deptOptions = res.data
      })
    },
    // 获取角色列表
    roleList(){
      listRole().then( res=> {
        this.roleOptions = res.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.isAdd =false
      this.isEdit = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        status: "0",
        remark: undefined,
        roleIds: []
      };
      this.resetForm("form")
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 新建按钮
    handleAdd() {
      this.reset()
      listUser().then(res => {
        this.open = true
        this.isAdd = true
        this.isEdit = false
        this.roleList()
        this.getTreeselect()
        this.title = "添加账号"
      })
    },
    // 编辑按钮
    handleUpdate(row) {
      const userId = row.userId
      getUser(userId).then(res => {
        // console.log(res)
        this.open = true
        this.isAdd = false
        this.isEdit = true
        this.roleList()
        this.getTreeselect()
        this.title = "编辑账号"
        this.form = res.data
        this.form.roleIds = res.roleIds
      })
    },
    // 编辑密码按钮
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(res => {
            this.$modal.msgSuccess("编辑成功，新密码是：" + value)
          })
        }).catch(() => {})
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            editUser(this.form).then(res => {
              this.$modal.msgSuccess("编辑成功")
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(res => {
              this.$modal.msgSuccess("新建成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 删除按钮
    handleDelete(row) {
      const userIds = row.userId
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(() => {
        delUser(userIds).then(()=>{
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
      }).catch(() => {})
    }
  }
}
</script>
